﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using AttributeRouting;
using AttributeRouting.Web.Mvc;
using Newtonsoft.Json.Linq;

using Invoicing.Model.Results;
using Invoicing.Model.Orders;
using Invoicing.Logic.Orders;
namespace Invoicing.Web.Management.Areas.Orders.Controllers
{
    [RouteArea("Orders")]
    [RoutePrefix("DealOrder")]
    [Authorize]
    public class DealOrderApiController : ApiController
    {
        [Route("GetLastPrice")]
        [HttpPost]
        public JsonResult<decimal> GetLastPrice(JObject request)
        {
            string errinfo = "";
            try
            {
                #region 收集参数
                var productID = request.Value<int>("productID");
                var customerID = request.Value<int>("customerID");
                #endregion

                var ret = DealOrderLogic.GetLastPrice(productID, customerID);
                return new JsonResult<decimal>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonResult<decimal>(0, errinfo, false);
        }
        [Route("SaveOrders")]
        [HttpPost]
        public JsonEntity<DealOrderModel> SaveOrders(JObject request)
        {
            string errinfo = "对不起！单据保存失败，出错原因：";
            try
            {
                #region 收集参数
                var order = new DealOrderModel() { Items = new DealOrderDetailCollection() };
                var items = request.GetValue("orderItems");
                if (items != null)
                {
                    order.NoteDate = request.Value<DateTime>("orderDate");
                    order.CustomerID = request.Value<int>("customerID");
                    order.OperatorUserID = Web.Global.WebContext.CurrentUser.ID;
                    order.Method = request.Value<int>("method");
                    order.Delivers = request.Value<string>("delivers");
                    order.Description = request.Value<string>("description");
                    order.AssociatedBookID = request.Value<int?>("bookID");
                    foreach (var it in items)
                    {
                        var dodm = new DealOrderDetailModel()
                        {
                            ProductID = it.Value<int>("productID"),
                            MaterialID = it.Value<int>("materialID"),
                            ProcessID = it.Value<int>("processID"),
                            Size = it.Value<string>("size")
                        };
                        if (!string.IsNullOrEmpty(it.Value<string>("unitPrice")))
                            dodm.UnitPrice = it.Value<decimal>("unitPrice");
                        if (!string.IsNullOrEmpty(it.Value<string>("quantity")))
                            dodm.Quantity = it.Value<decimal>("quantity");
                        if (!string.IsNullOrEmpty(it.Value<string>("weightQuantity")))
                            dodm.WeightQuantity = it.Value<decimal>("weightQuantity");
                        if (!string.IsNullOrEmpty(it.Value<string>("weightUnitPrice")))
                            dodm.WeightUnitPrice = it.Value<decimal>("weightUnitPrice");
                        order.Items.Add(dodm);
                    }
                }
                else
                    throw new Utils.InvoicingException("没有定单内容。");
                
                #endregion

                var ret = DealOrderLogic.NewOrder(order);
                return new JsonEntity<DealOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo += lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntity<DealOrderModel>(null, errinfo, false);
        }
        [Route("GetOrders")]
        [HttpPost]
        public JsonEntitySet<DealOrderModel> GetOrders(JObject request)
        {
            string errinfo = "no data";
            try
            {
                #region 收集参数
                DealOrderQuery sea = new DealOrderQuery();
                sea.PageSize = request.Value<int>("pageSize");
                sea.PageIndex = request.Value<int>("pageIndex");
                sea.GetCustomer = request.Value<bool>("getCustomer");
                sea.CustomerID = request.Value<int>("customerID");
                sea.OrderNo = request.Value<string>("orderNo");
                sea.GetOperator = request.Value<bool>("getOperator");
                var orderStatus = request.Value<string>("orderStatus");
                if (!string.IsNullOrEmpty(orderStatus))
                    sea.OrderStatus = orderStatus.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
                var odb = request.Value<string>("orderDateBefore");
                if (!string.IsNullOrEmpty(odb))
                    sea.OrderDateBefore = DateTime.Parse(odb);
                var oda = request.Value<string>("orderDateAfter");
                if (!string.IsNullOrEmpty(oda))
                    sea.OrderDateAfter = DateTime.Parse(oda);
                var orderMethod = request.Value<string>("orderMethod");
                if (!string.IsNullOrEmpty(orderMethod))
                    sea.Method = orderMethod.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
                #endregion

                var ret = DealOrderLogic.GetOrders(sea);
                return new JsonEntitySet<DealOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntitySet<DealOrderModel>(null, errinfo, false);
        }
        [Route("GetOrderWithProductOrders")]
        [HttpPost]
        public JsonEntity<DealOrderModel> GetOrderWithProductOrders(JObject request)
        {
            string errinfo = "no data";
            try
            {
                var orderNo = request.Value<string>("orderNo");
                var ret = DealOrderLogic.GetOrderWithProductOrders(orderNo);
                return new JsonEntity<DealOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntity<DealOrderModel>(null, errinfo, false);
        }
        [Route("CancelOrder")]
        [HttpPost]
        public JsonResult<bool> CancelOrder(JObject request)
        {
            string errinfo = "撤消单据失败";
            try
            {
                #region 收集参数
                var orderNo = request.Value<string>("orderNo");
                #endregion

                var ret = DealOrderLogic.CancelOrder(orderNo);
                return new JsonResult<bool>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonResult<bool>(false, errinfo, false);
        }
        [Route("LoadBookOrder")]
        [HttpPost]
        public JsonEntity<DealOrderModel> LoadBookOrder(JObject request)
        {
            string errinfo = "no data";
            try
            {
                var orderNo = request.Value<string>("orderNo");
                var order = BookOrderLogic.GetOrder(orderNo);
                if (order != null)
                {
                    var ret = new DealOrderModel() { Items = new DealOrderDetailCollection() };
                    ret.CustomerID = order.CustomerID;
                    ret.Customer = order.Customer;
                    ret.AssociatedBookID = order.ID;
                    order.Items.ForEach(p =>
                    {
                        ret.Items.Add(new DealOrderDetailModel()
                        {
                            Product = p.Product,
                            Size = p.Size,
                            Material = p.Material,
                            Process = p.Process,
                            Quantity = p.Quantity
                        });
                    });
                    return new JsonEntity<DealOrderModel>(ret);
                }
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntity<DealOrderModel>(null, errinfo, false);
        }
    }
}
